﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Globalization;
using System.Collections.ObjectModel;
using University.Workshop.Model;

namespace University.Workshop.DataAccess
{
    public static class ImageUploadHandler
    {
        public static void SaveImageFile(
              HttpPostedFile clientFile,
              String saveImagePath,
              int maxImageWidth)
        {
            if (clientFile != null)
            {
                Bitmap sourceImage =
                  new Bitmap(clientFile.InputStream);
                SaveImageFile(sourceImage, saveImagePath, maxImageWidth);
            }
        }

        public static void SaveImageFile(
            System.Drawing.Image sourceImage,
            String saveImagePath,
            int maxImageWidth)
        {
            // Resize if source image width is greater than the max:
            System.Drawing.Image resizedImage = null;
            try
            {
                if (sourceImage != null)
                {
                    if (sourceImage.Width > maxImageWidth)
                    {
                        int newImageHeight = (int)(sourceImage.Height *
                          ((float)maxImageWidth / (float)sourceImage.Width));
                        resizedImage = new Bitmap(maxImageWidth, newImageHeight);
                        Graphics gr = Graphics.FromImage(resizedImage);
                        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        gr.DrawImage(sourceImage, 0, 0, maxImageWidth, newImageHeight);
                        // Save the resized image:
                        resizedImage.Save(saveImagePath, FileExtensionToImageFormat(saveImagePath));
                    }
                    else
                    {
                        // Save the source image (no resizing necessary):
                        sourceImage.Save(saveImagePath, FileExtensionToImageFormat(saveImagePath));
                    }
                }
            }
            catch (Exception)
            {
                throw new DataAccessException("Error saving image");
            }
            finally
            {
                if (resizedImage != null)
                {
                    resizedImage.Dispose();
                }
            }
        }

        private static ImageFormat FileExtensionToImageFormat(String filePath)
        {
            String ext = Path.GetExtension(filePath).ToLower(CultureInfo.CurrentCulture);
            ImageFormat result = ImageFormat.Jpeg;
            switch (ext)
            {
                case ".gif":
                    result = ImageFormat.Gif;
                    break;
                case ".png":
                    result = ImageFormat.Png;
                    break;

            }
            return result;
        }

        public static void UploadImages(Collection<HttpPostedFile> images, HttpServerUtility server, long productId)
        {
            if (server != null && images != null)
            {
                foreach (HttpPostedFile file in images)
                {
                    string fileName = Path.GetFileName(file.FileName);
                    string thumbPath = server.MapPath("~/Thumbnails/") + productId + "/";
                    string imagePath = server.MapPath("~/Images/") + productId + "/";
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        if (!Directory.Exists(thumbPath))
                        {
                            Directory.CreateDirectory(imagePath);
                        }
                        if (!Directory.Exists(thumbPath))
                        {
                            Directory.CreateDirectory(thumbPath + productId + "/");
                        }
                        SaveImageFile(file, server.MapPath("~/Images/") + productId + "/" + fileName, 500);
                        SaveImageFile(file, server.MapPath("~/Thumbnails/") + productId + "/" + fileName, 100);
                    }
                }
            }
        }

        public static void UploadCommentImage(HttpPostedFile images, HttpServerUtility server, long comment)
        {
            if (server != null && images != null)
            {

                string fileName = Path.GetFileName(images.FileName);
                string thumbPath = server.MapPath("~/Thumbnails/C") + comment + "/";
                string imagePath = server.MapPath("~/Images/C") + comment + "/";
                if (!String.IsNullOrEmpty(fileName))
                {
                    if (!Directory.Exists(thumbPath))
                    {
                        Directory.CreateDirectory(imagePath);
                    }
                    if (!Directory.Exists(thumbPath))
                    {
                        Directory.CreateDirectory(thumbPath + comment + "/");
                    }
                    SaveImageFile(images, server.MapPath("~/Images/C") + comment + "/" + fileName, 500);
                    SaveImageFile(images, server.MapPath("~/Thumbnails/C") + comment + "/" + fileName, 100);
                }
            }
        }

        public static void DeleteImages(Collection<string> existing, HttpServerUtility server, long productId)
        {
            if (server != null && existing != null)
            {
                string thumbDir = server.MapPath("~/Thumbnails/") + productId + "/";
                string imageDir = server.MapPath("~/Images/") + productId + "/";
                foreach (string name in existing)
                {
                    File.Delete(thumbDir + name);
                    File.Delete(imageDir + name);
                }
            }
        }

        public static void UploadUserImages(Collection<HttpPostedFile> images, HttpServerUtility server, long userId)
        {
            if (server != null && images != null)
            {
                foreach (HttpPostedFile file in images)
                {
                    string fileName = Path.GetFileName(file.FileName);
                    string thumbPath = server.MapPath("~/Thumbnails/U") + userId + "/";
                    string imagePath = server.MapPath("~/Images/U") + userId + "/";
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        if (!Directory.Exists(thumbPath))
                        {
                            Directory.CreateDirectory(imagePath);
                        }
                        if (!Directory.Exists(thumbPath))
                        {
                            Directory.CreateDirectory(thumbPath + userId + "/");
                        }
                        SaveImageFile(file, server.MapPath("~/Images/U") + userId + "/" + fileName, 500);
                        SaveImageFile(file, server.MapPath("~/Thumbnails/U") + userId + "/" + fileName, 100);
                    }
                }
            }
        }       

        public static void DeleteUserImage(string name, HttpServerUtility server, long userId)
        {
            if (server != null && name != null)
            {
                string thumbDir = server.MapPath("~/Thumbnails/U") + userId + "/";
                string imageDir = server.MapPath("~/Images/U") + userId + "/";
                File.Delete(thumbDir + name);
                File.Delete(imageDir + name);
            }
        }

        public static void UploadHavingPath(string path, HttpServerUtility server, long userId)
        {
            FileStream rFile = null;
            if (server == null || path == null)
            {
            }
            else
            {
                try
                {
                    rFile = new FileStream(path, FileMode.Open);

                    long nFileLen = rFile.Length;

                    byte[] myData = new byte[nFileLen];
                    rFile.Read(myData, 0, (int) nFileLen);

                    string fileName = Path.GetFileName(path);

                    Bitmap sourceImage =
                        new Bitmap(rFile);
                    SaveImageFile(sourceImage, server.MapPath("~/Images/U") + userId + "/" + fileName, 500);
                    SaveImageFile(sourceImage, server.MapPath("~/Thumbnails/U") + userId + "/" + fileName, 100);
                }
                catch (Exception)
                {
                    throw new BadImageFormatException("Error opening Big Image");
                }
                finally
                {
                    if (rFile != null)
                    {
                        rFile.Dispose();
                    }
                }
            }
        }
    }
}
